<script>
import { queryBtnList } from '@/api/permissions'
const isPermission = process.env.VUE_APP_PERMISSION === 'open'
export default {
  name: 'CPermission',
  abstract: true,
  props: {
    code: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      permissionList: [],
      tipText: ''
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    getPermissionList() {
      const code = this.code
      if (!isPermission || code === '') return
      const menuCode = this.$route.query.menuCode
      queryBtnList(menuCode, code).then(res => {
        this.permissionList = res.data.groovyList.map(e => e.buttonCode)
        this.tipText = ''
      }).catch(e => {
        this.tipText = e.message ? '权限错误：' + e.message : '获取权限错误！'
      })
    }
  },
  render(h) {
    if (this.tipText) {
      return h('el-alert', { props: { title: this.tipText, type: 'error', closable: false }})
    }
    const vnode = this.$scopedSlots.default instanceof Function ? this.$scopedSlots.default(this.permissionList) : []
    let pVnode = []
    if (isPermission && this.code !== '') {
      for (const node of vnode) {
        const attrs = ((node.data || {}).attrs || {})
        if (this.permissionList.includes(attrs.optCode || attrs['opt-code'])) {
          pVnode.push(node)
        }
      }
    } else {
      pVnode = vnode
    }
    return h('div', pVnode)
  }
}
</script>
